const mysql = require('mysql');
const md5 = require('md5');
const moment = require('moment');

const MOMENT_FORMAT_STR = 'YYYY-MM-DD HH:mm:ss.SSS';
const MOMENT_FORMAT = 'YYYY-MM-DD HH:mm:ss';

const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'books'
});

connection.connect();

connection.beginTransaction((err)=>{
    if (err) throw err;
    connection.query('INSERT INTO t_book SET name=?', '测试', (err, results, field)=>{
        if (err) {
            return connection.rollback(()=>{
                throw err;
            });
        }

        let log = 't_book 新增一条数据, id: ' + results.insertId;
        var _now = moment();
        let logData = {
            id: md5(_now.format(MOMENT_FORMAT_STR)),
            log: log,
            createtime: _now.format(MOMENT_FORMAT)
        };
        connection.query('INSERT INTO t_logs SET ?', logData, (err, results, field)=>{
            if (err) {
                return connection.rollback(()=>{
                    throw err;
                });
            }
            connection.commit((err)=>{
                if (err) {
                    return connection.rollback(()=>{
                        throw err;
                    });
                }
                console.log('success!');
                connection.end();
            });
        });
    });
});

// connection.end();